class RentalController < ApplicationController
  before_filter :authorize
  before_filter :setup_list

def rental
  @title = "Rental"
  if params[:cust_search] == nil
      @customers = Customer.find(:all)
  else
      @customers = Customer.search params[:cust_search]
  end
  if params[:equip_search] == nil
      @equipment = Equipment.find(:all)
  else
      @equipment = Equipment.search params[:equip_search]
  end
end

def customer
  session[:customer] = Customer.find(params[:id])
  redirect_to :action => "rental"
end

def add
  session[:cart] << Equipment.find(params[:id])
  session[:cart].uniq!
  redirect_to :action => "rental"
end

def remove
  item = Equipment.find(params[:id])
  session[:cart].delete_if {|x| x == item}
  redirect_to :action => "rental"
end

def reserve
  @user = Employee.find_by_id(session[:employee_id])
  @date = Date.new(Time.now.year,Time.now.month,Time.now.day)
  @rental = Rental.new({
	"date_created"=>@date,
	"customer_id"=>session[:customer].id,
	"rental_status"=>0,
	"employee_id"=>@user.id})
  if @rental.save
    session[:cart].each do |item|
      item.rental_id = @rental.id
      item.customer_id = @rental.customer_id
      item.save
    end
    @rental = Rental.new
    redirect_to :controller => "employee"
  end
end

def checkout
  if param_posted?(:dates)
    redirect_to :controller => "employee"
  end
end

def checkoutback
  if param_posted?(:rental)
  @user = Employee.find_by_id(session[:employee_id])
  @date = Date.new(Time.now.year,Time.now.month,Time.now.day)
  @rental = Rental.new({
	"date_created"=>@date,
	"customer_id"=>session[:customer].id,
	"rental_status"=>0,
	"employee_id"=>@user.id})
  if @rental.update_attributes(params[:rental])
  if @rental.save
    session[:cart].each do |item|
      item.rental_id = @rental.id
      item.customer_id = @rental.customer_id
      item.save
    end
    #@rental = Rental.new
    redirect_to :controller => "employee"
  end
  end
  end
end

def checkin
  @title = "Checkin"
  @rentals = Rental.find(:all)
end

def rental_details
  @rental = Rental.find_by_id(params[:id])
  @title = "#{@rental.id} details"
  @equipment = Equipment.find(:all)
  @customer = Customer.find_by_id(params[:id])
end

def list_rentals
  @title = "Rentals"
  if params[:search] == nil
      @rentals = Rental.find(:all)
  else
      @rentals = Rental.search params[:search]
  end
end

private
  def param_posted?(symbol)
    request.post? and params[symbol]
  end

end

